package com.sprucetec.live.block;

import com.sprucetec.live.common.dto.business.LiveChatDto;
import com.sprucetec.live.mcq.McqBusinessMemoryMap;
import com.sprucetec.live.service.LiveChatService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ChatAddMessageConsumer
 * @Description: 聊天发送mcq端阻塞队列，目的是将发送到mcq的消息队列化，减少mcq并发压力
 * @Author Kenny
 * @Date 2020/5/28
 **/
@Data
@Slf4j
@Component
@Scope("prototype")
public class ChatAddMessageConsumer implements Runnable {

    private BlockingQueue<LiveChatDto> queue;//阻塞队列
    private volatile boolean cancelled = false;


    @Value("${system.high.concurrency.addChatByQueue.delayTime:10}")
    private Integer delayTime;

    private static final Integer BlockQueueRunDeadTime = 1000; //30分钟如果没有任何人发送消息，则关闭相关线程

    private Integer cursor = 0;

    private LiveChatDto liveChatDto;
    private String videoId = null;

    @Autowired
    private LiveChatService liveChatService;

    @Override
    public void run() {
        try {
            while (!cancelled) {
                //有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回null
                LiveChatDto liveChatDto = queue.poll(2, TimeUnit.SECONDS);
                Thread.sleep(delayTime);
                if (liveChatDto != null) {
                    try {
                        liveChatService.chatToMCQ(liveChatDto);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    cursor++;
                    if (cursor >= BlockQueueRunDeadTime) {
                        cancel();
                    }
                }
            }
        } catch (InterruptedException e) {
            log.info("消息阻塞队列中消费失败=>{}", e.toString());
        }
    }

    /**
     * 结束线程
     */
    public void cancel() {
        cancelled = true;
        McqBusinessMemoryMap.addChatQueueHashMap.remove(videoId);
    }
}
